﻿using rmTest.Common;
using rmTest.Common.ConstUtil;
using Ruanmou.Framework.Log;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ProgramTest
{
    public class TaskFactoryShow
    {
        private static readonly object OpenLock = new object();
        public static void Show()
        {
            bool isMonitor = true;
            try
            {
                List<PersonAction> scList = InitData.PersonActions;
                Stopwatch watch = new Stopwatch();
                watch.Start();

                CancellationTokenSource cts = new CancellationTokenSource();

                #region 监控线程
                Task.Run(() =>
                {
                    int randomNumber = 0;
                    int year = DateTime.Now.Year;
                    while (isMonitor && randomNumber != year)
                    {
                        randomNumber = new Random(randomNumber).Next(2000, 2100);
                        //Console.Write(randomNumber);
                        Thread.Sleep(100);
                    }
                    if (isMonitor)
                    {
                        //表示条件吻合了  得去取消别的线程
                        LogHelper.LogConsole("天降雷霆灭世，天龙八部的故事就此结束....", ConsoleColor.DarkRed);
                        cts.Cancel();//监控线程没人管，会一直运行下去，即使天龙八部早就结束
                    }
                    else
                    {
                        LogHelper.LogConsole("取消监控", ConsoleColor.White);
                    }
                });
                #endregion

                bool isOpen = false;
                List<Task> taskList = new List<Task>();
                TaskFactory taskFactory = new TaskFactory();
                foreach (var person in scList)
                {
                    taskList.Add(
                        taskFactory.StartNew(
                            s =>
                            {
                                if (!cts.IsCancellationRequested)
                                {
                                    LogHelper.LogConsole($"我是：{person.Name}；", person.Color);
                                }
                                for (int i = 0; i < person.Actions.Length; i++)
                                {
                                    if (cts.IsCancellationRequested)
                                    {
                                        break;
                                    }
                                    if (i == 0)//控制拉开序幕的事儿
                                    {
                                        if (!isOpen)//拉开序幕之后，再也不用等待了
                                        {
                                            lock (OpenLock)//多个线程都进来
                                            {
                                                if (!isOpen)//还没拉开序幕
                                                {
                                                    if (cts.IsCancellationRequested)
                                                    {
                                                        break;
                                                    }
                                                    LogHelper.LogConsole(person.Actions[i], person.Color);
                                                    LogHelper.LogConsole("天龙八部就此拉开序幕。。。。", ConsoleColor.White);
                                                    isOpen = true;
                                                }
                                                else
                                                {
                                                    if (cts.IsCancellationRequested)
                                                    {
                                                        break;
                                                    }
                                                    LogHelper.LogConsole(person.Actions[i], person.Color);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if (cts.IsCancellationRequested)
                                            {
                                                break;
                                            }
                                            LogHelper.LogConsole(person.Actions[i], person.Color);
                                        }
                                    }
                                    else
                                    {
                                        LogHelper.LogConsole(person.Actions[i], person.Color);
                                    }
                                }
                            }, person.Name, cts.Token));
                }
                taskList.Add(taskFactory.ContinueWhenAny(taskList.ToArray(), t =>
                {
                    if (cts.IsCancellationRequested)
                    {
                        return;
                    }
                    LogHelper.LogConsole($"{t.AsyncState}已经做好准备啦。。。。", ConsoleColor.White);
                }
                ));
                taskList.Add(taskFactory.ContinueWhenAll(taskList.ToArray(), t =>
                {
                    if (cts.IsCancellationRequested)
                    {
                        return;
                    }
                    LogHelper.LogConsole($"中原群雄大战辽兵，忠义两难一死谢天。。。。", ConsoleColor.White);
                }
               //这里可以统计的时间
               ));

                Task.WaitAll(taskList.ToArray());
                watch.Stop();
                if (!cts.IsCancellationRequested)
                {
                    //return
                    LogHelper.LogConsole($"整个天龙八部的故事一共花费了{watch.ElapsedMilliseconds}ms", ConsoleColor.White);
                }

            }
            catch (Exception ex)
            {
                LogHelper.LogConsole(ex.Message, ConsoleColor.DarkGray);
            }
            finally
            {
                isMonitor = false;
            }

            Console.ReadKey();
        }

    }
}
